package com.mcptt.db.op;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

import com.mcptt.db.DBProvider;
import com.mcptt.db.DbConst;
import com.mcptt.db.model.ConfigFileInfo;

public class GroupConfigFileDbOperator {

    public static String THIS_FILE = "GroupConfigFileDbOperator";
    private Context ctx = null;

    public GroupConfigFileDbOperator(Context ctx)
    {
	this.ctx = ctx;
    }

    public ConfigFileInfo getGroupConfigFileInfoByGroupName(String groupName)
    {
	ContentResolver cr = ctx.getContentResolver();
	String selection = DbConst.COL_GroupName + "=?";
	ConfigFileInfo info = null;

	Cursor cursor = null;
	try 
	{
	    cursor = cr.query(DbConst.GROUP_CONFIG_URI,
		    DBProvider.GROUP_CONFIG_FULL_PROJECTION, selection,
		    new String[] { groupName }, DbConst.COL_GroupName );

	    if(cursor !=null
		    && cursor.getCount() > 0)
	    {			
		if(cursor.moveToFirst())
		{
		    info = new ConfigFileInfo(cursor);
		}
	    }
	} 
	catch (Exception e) 
	{
	    // TODO: handle exception
	}
	finally
	{
	    if(cursor != null)
	    {
		cursor.close();
		cursor = null;
	    }
	}

	return info;
    }


    public void addGroupConfigFileInfo(ConfigFileInfo info)
    {
	String groupName = info.getFileName();
	ContentResolver cr = ctx.getContentResolver();
	String selection = DbConst.COL_GroupName + "=?";	

	Cursor cursor = null;
	try 
	{
	    cursor = cr.query(DbConst.GROUP_CONFIG_URI,
		    DBProvider.GROUP_CONFIG_FULL_PROJECTION, selection,
		    new String[] {groupName}, null);
	    if (cursor == null
		    || cursor.getCount() <= 0)
	    {
		cr.insert(DbConst.GROUP_CONFIG_URI, info.getGroupContentValues());
	    }
	} 
	catch (Exception e) 
	{
	    e.printStackTrace();
	    // TODO: handle exception
	}
	finally
	{
	    if(cursor != null)
	    {
		cursor.close();
		cursor = null;
	    }
	}
    }
    public void deleteAllConfigFileInfo()
    {
	ContentResolver cr = ctx.getContentResolver();
	cr.delete(DbConst.GROUP_CONFIG_URI, null,null);
    }

    public void updateConfigFileInfo(ConfigFileInfo info)
    {
	String groupName = info.getFileName();
	ContentResolver cr = ctx.getContentResolver();
	String selection = DbConst.COL_GroupName + "=?";
	int ret = cr.update(DbConst.GROUP_CONFIG_URI, info.getContentValues(), selection, new String[] {groupName});
	if(ret <= 0)
	{
	    addGroupConfigFileInfo(info);
	}
    }
}
